<!DOCTYPE html>
<script src='../../resources/testharness.js'></script>
<script src='../../resources/testharnessreport.js'></script>

<script>

function loadingDonePromise() {
  return new Promise(function(resolve) {
    function handler(e) {
      document.fonts.removeEventListener('loadingdone', handler);
      resolve(e);
    };
    document.fonts.addEventListener('loadingdone', handler);
  });
}

promise_test(() => {
  let face = new FontFace('face1', 'url(../../resources/Ahem.ttf)', {});
  assert_equals(face.status, 'unloaded');

  let faceLoaded = face.load();
  assert_equals(face.status, 'loading');
  assert_equals(document.fonts.status, 'loaded')

  let loadingDone = loadingDonePromise();
  document.fonts.add(face);
  assert_equals(document.fonts.status, 'loading');

  return Promise.all(
      [faceLoaded, loadingDone, document.fonts.ready]).then(() => {
    assert_equals(document.fonts.status, 'loaded');
    assert_equals(face.status, 'loaded');
  });
}, 'document.fonts.add() called while a FontFace is loading.');

promise_test(() => {
  assert_equals(document.fonts.status, 'loaded');

  let face = new FontFace('face2', 'url(../../resources/Ahem.ttf)', {});
  assert_equals(face.status, 'unloaded');

  document.fonts.add(face);
  let faceLoaded = face.load();
  assert_equals(document.fonts.status, 'loading');

  let loadingDone = loadingDonePromise();
  document.fonts.delete(face);

  // Deleting a font from the document should not change its or the document's
  // loading status until the loadingdone event is fired.
  assert_equals(document.fonts.status, 'loading');
  assert_equals(face.status, 'loading');

  return Promise.all(
      [faceLoaded, loadingDone, document.fonts.ready]).then(() => {
    assert_equals(document.fonts.status, 'loaded');
    assert_equals(face.status, 'loaded');
  });
}, 'document.fonts.delete() called while a FontFace is loading.');

promise_test(() => {
  assert_equals(document.fonts.status, 'loaded');

  let face = new FontFace('face3', 'url(../../resources/Ahem.ttf)', {});
  assert_equals(face.status, 'unloaded');

  document.fonts.add(face);
  let faceLoaded = face.load();
  assert_equals(document.fonts.status, 'loading');

  let loadingDone = loadingDonePromise();
  document.fonts.clear();
  assert_equals(document.fonts.status, 'loading');
  assert_equals(face.status, 'loading');

  return Promise.all(
      [faceLoaded, loadingDone, document.fonts.ready]).then(() => {
    assert_equals(document.fonts.status, 'loaded');
    assert_equals(face.status, 'loaded');
  });
}, 'document.fonts.clear() called while a FontFace is loading.');

</script>
